
#include "io.h"
#include "inp.h"

#define   DEBOUNCE				4		/* how many times check the key every 10mS*/
#define   LONG_PRESS_TIME		3 /* x 1000ms maximum 15 */

#define   LO		0
#define   HI		1	

unsigned char InpDig_Event;

/* typedef struct */
/* {	 */
/* 		volatile unsigned char *PORT; */
/* 		unsigned Pin					: 7; */
/* 		unsigned State					: 1; */
/* 		unsigned Filter    			: 4; */
/* 		unsigned Filter_Long  		: 4; */
/* }INP_STATE; */

typedef struct
{	
		volatile unsigned int *PORT;
		unsigned Pin	: 7;
		unsigned State	: 1;
		unsigned char Filter;
		unsigned char Filter_Long;
}pin_input_t;

#define   INPUTS_AMOUNT		2

#define   PORT_DIR_SHIFT	0x01

pin_input_t Inputs[INPUTS_AMOUNT] = 
{
	{(volatile unsigned int *)ADDR_PORTD_INP, 4,	0, 0, 0},  /* inp learn */
};

void inputs_init( void )
{
	unsigned char i;
	volatile unsigned char *p;

	/* set direction as input */
	for ( i = 0; i < INPUTS_AMOUNT; i++ )
	{
		p = Inputs[i].PORT + PORT_DIR_SHIFT;  
		*p &= ~(1<<Inputs[i].Pin);
	}
}

#define   PIN_READ()			(*Inputs[i].PORT & (1<<Inputs[i].Pin))
#define   PIN_FILTER 		Inputs[i].Filter
#define   PIN_FILTER_LONG 	Inputs[i].Filter_Long
#define   PIN_STATE 			Inputs[i].State


unsigned char input_get_state ( unsigned char input_num )
{
	if ( input_num >= INPUTS_AMOUNT )
		return 0;

	return Inputs[input_num].State;
}

void Inp_Drive( void )
{
	InpDig_Event = 0;

/* 	if ( TIME_10ms == 0 ) */
/* 		return; */

	for ( i = 0; i < INPUTS_AMOUNT; i++ )
	{
		if ( PIN_STATE == LO )
		{
			if ( PIN_READ() )
			{
				if ( ++PIN_FILTER >= DEBOUNCE )
				{
					PIN_STATE = HI;
					PIN_FILTER = 0;
					PIN_FILTER_LONG = 0;
					InpDig_Event = INPUT_HIGH|i;
					break;
				}
			}
			else
			{
				PIN_FILTER = 0;

				if ( TIME_1000ms && (PIN_FILTER_LONG < LONG_PRESS_TIME) && (++PIN_FILTER_LONG >= LONG_PRESS_TIME) )
				{
					//PIN_FILTER_LONG = 0;
					InpDig_Event = INPUT_LOW_LONG|i;
					break;
				}
			}
		}
		else
		{
			if ( !PIN_READ() )
			{
				if ( ++PIN_FILTER > 14 )
				{
					PIN_STATE = LO;
					PIN_FILTER = 0;
					PIN_FILTER_LONG = 0;
					InpDig_Event = INPUT_LOW|i;
					break;
				}
			}
			else
			{
				PIN_FILTER = 0;
				if ( TIME_1000ms && (PIN_FILTER_LONG < LONG_PRESS_TIME) && (++PIN_FILTER_LONG >= LONG_PRESS_TIME) )
				{					
					InpDig_Event = INPUT_HIGH_LONG|i;
					break;
				}

			}
		}
	}

}



















/* 	if ( Remote_Pressed_Key ) */
/* 	{ */
/* 		 i = Remote_Pressed_Key & 0x7F; */
		 
/* 		if (  i < INPUTS_AMOUNT ) */
/* 		{  */
/* 			InpDig_Event = Inp_Pressed_Key|i;  */
/* 		} */
		
/* 		return ; */
/* 	} */
